package com.spic.business.plan.inspection.service.impl;

import com.spic.business.common.datascope.anotation.BusinessDataScope;
import com.spic.business.plan.emergencycode.service.impl.EmergencyCodeServiceImpl;
import com.spic.business.plan.inspection.domain.PlanInspection;
import com.spic.business.plan.inspection.domain.PlanInspectionHistory;
import com.spic.business.plan.inspection.mapper.PlanInspectionMapper;
import com.spic.business.plan.inspection.service.IPlanInspectionService;
import com.spic.business.plan.supplies.domain.PlanSupplies;
import com.spic.business.plan.supplies.domain.PlanSuppliesDto;
import com.spic.business.plan.supplies.mapper.PlanSuppliesMapper;
import com.spic.common.core.domain.R;
import com.spic.common.core.utils.DateUtils;
import com.spic.common.core.utils.SecurityUtils;
import com.spic.common.core.utils.StringUtils;
import com.spic.system.api.RemoteNoticeInfoService;
import com.spic.system.api.RemoteUserService;
import com.spic.system.api.domain.SysNoticeInfo;
import com.spic.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 应急物资检查Service业务层处理
 *
 * @author spic
 * @date 2021-10-28
 */
@Service
public class PlanInspectionServiceImpl implements IPlanInspectionService {
    @Autowired
    private PlanInspectionMapper planInspectionMapper;
    @Autowired
    private EmergencyCodeServiceImpl emergencyCodeService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private PlanSuppliesMapper planSuppliesMapper;
    @Autowired
    private RemoteNoticeInfoService remoteNoticeInfoService;
    @Autowired
    private PlanInspectionServiceImpl planInspectionServiceImpl;
    /**
     * 查询应急物资检查
     *
     * @param id 应急物资检查主键
     * @return 应急物资检查
     */
    @Override
    public PlanInspection selectPlanInspectionById(Long id) {
        PlanInspection materialName =  planInspectionMapper.selectPlanInspectionById(id);
        Long bed = materialName.getMaterialId();
        if (bed != null && !"".equals(bed)) {

            PlanSupplies planSupplies = planSuppliesMapper.selectPlanSuppliesById(bed);
            if (planSupplies != null) {
                materialName.setMonad(planSupplies.getMonad());
                materialName.setQuantityStock(planSupplies.getQuantityStock());
            }
        }
        return materialName;
    }

    /**
     * 查询应急物资检查
     *
     * @param id 应急物资检查主键
     * @return 应急物资检查
     */
    @Override
    public PlanInspectionHistory getInspectionHistoryInfo(Long id) {
        PlanInspectionHistory materialName =  planInspectionMapper.getInspectionHistoryInfo(id);

        return materialName;
    }




    public List<PlanSupplies> selectTransfer(PlanSupplies planSupplies) {
        return planSuppliesMapper.selectTransfer(planSupplies);
    }

    /**
     * 查询应急物资检查列表
     *
     * @param planInspection 应急物资检查
     * @return 应急物资检查
     */
    @Override
    @BusinessDataScope(menuPath = "business/plan/inspection/index")
    public List<PlanInspection> selectPlanInspectionList(PlanInspection planInspection) {

        List<PlanInspection> planInspections = planInspectionMapper.selectPlanInspectionList(planInspection);
        if (StringUtils.isNotNull(planInspections) && planInspections.size() > 0) {
            planInspections.forEach(planInspectionsList -> {
                String associateDept = planInspectionsList.getRummager();
                if (associateDept != null && !"".equals(associateDept)) {
                    Long lives = Long.parseLong(associateDept);
                    R<SysUser> sysAcceptor = remoteUserService.getUserById(lives);
                    if (sysAcceptor.getData() != null) {
                        planInspectionsList.setRummager(sysAcceptor.getData().getNickName());
                    }
                }
            });
//            planInspections.forEach(materialName -> {
//                Long bed = materialName.getMaterialId();
//                if (bed != null && !"".equals(bed)) {
//
//                    PlanSupplies planSupplies = planSuppliesMapper.selectPlanSuppliesById(beds);
//                    if (planSupplies != null) {
//                        materialName.setMaterialName(planSupplies.getMaterialName());
//                    }
//                }
//            });
        }
        return planInspections;
    }



    /**
     * 查询应急物资检查列表
     *
     * @param planInspection 应急物资检查
     * @return 应急物资检查
     */
    @Override
    public List<PlanInspectionHistory> selectPlanInspectionHistoryList(PlanInspectionHistory planInspectionHistory) {

        List<PlanInspectionHistory> planInspections = planInspectionMapper.selectPlanInspectionHistoryList(planInspectionHistory);

        return planInspections;
    }




    /**
     * 新增应急物资检查
     *
     * @param planInspection 应急物资检查
     * @return 结果
     */

    @Override
    public int insertPlanInspection(PlanInspection planInspection) {

        planInspection.setCreateTime(DateUtils.getNowDate());
        planInspection.setCreateBy(SecurityUtils.getUserId()+"");
        planInspection.setUpdateBy(SecurityUtils.getUserId()+"");
        planInspection.setUpdateTime(DateUtils.getNowDate());

        planInspectionMapper.insertPlanInspection(planInspection);



        //更新头部表所选物资信息
        PlanInspection headMaterial = new PlanInspection();
        headMaterial.setInspectionHistoryId(planInspection.getInspectionHistoryId());

        List<PlanInspection> resultList=planInspectionMapper.selectPlanInspectionList(headMaterial);
        if(resultList !=null && resultList.size()>0){

            StringJoiner materialIdJoiner = new StringJoiner(",");
            StringJoiner materialNameJoiner = new StringJoiner(",");

            resultList.forEach(item -> {
                //将实体中的某个字段获取到 添加到stringJoiner
                materialIdJoiner.add(item.getMaterialId().toString());
                materialNameJoiner.add(item.getMaterialName());
            });

            String materialIds = materialIdJoiner.toString();
            String materialNames = materialNameJoiner.toString();

            PlanInspectionHistory planInspectionHistory = planInspectionMapper.getInspectionHistoryInfo(planInspection.getInspectionHistoryId());

            planInspectionHistory.setMaterialId(materialIds);
            planInspectionHistory.setMaterialName(materialNames);

            planInspectionMapper.updateInspectionHistory(planInspectionHistory);
        }

//        String materiaLcode = emergencyCodeService.getCodeNames();
//        planInspection.setMaterialCode(materiaLcode);
//        planInspection.setPerformance("1");
//        PlanSupplies planSupplies = new PlanSupplies();
//        List<PlanSupplies> list = planInspectionServiceImpl.selectTransfer(planSupplies);
//        list.forEach(item -> {
//            planInspection.setMaterialName(item.getId().toString());
//            planInspectionMapper.insertPlanInspection(planInspection);
//        });
        return 1;
    }


    @Override
    public int insertPlanInspectionHistory(PlanInspectionHistory planInspectionHistory) {


        planInspectionHistory.setCreateTime(DateUtils.getNowDate());
        planInspectionHistory.setCreateBy(SecurityUtils.getUserId()+"");
        planInspectionHistory.setUpdateBy(SecurityUtils.getUserId()+"");
        planInspectionHistory.setUpdateTime(DateUtils.getNowDate());
        planInspectionMapper.insertPlanInspectionHistory(planInspectionHistory);

        Long inspectionHistoryId = planInspectionHistory.getId();


        String[] materialIds = planInspectionHistory.getMaterialId().split(",");


        for (int i = 0; i < materialIds.length; i++) {

            Long id=Long.parseLong(materialIds[i].toString());
            PlanSupplies planSupplies = planSuppliesMapper.selectPlanSuppliesById(id);

            PlanInspection planInspection = new PlanInspection();
            //检查记录头部表主键
            planInspection.setInspectionHistoryId(inspectionHistoryId);
            //检查说明
            planInspection.setInspectionCertificate(planInspectionHistory.getProblemDescription());
            planInspection.setCycle(planInspectionHistory.getCycle());
            planInspection.setCreateTime(DateUtils.getNowDate());
            planInspection.setMaterialCode(planSupplies.getMaterialCode());
            planInspection.setPerformance("1");
            planInspection.setMaterialId(id);
            planInspection.setMaterialName(planSupplies.getMaterialName());
            planInspection.setCreateTime(DateUtils.getNowDate());
            planInspection.setCreateBy(SecurityUtils.getUserId()+"");
            planInspection.setUpdateBy(SecurityUtils.getUserId()+"");
            planInspection.setUpdateTime(DateUtils.getNowDate());
            planInspectionMapper.insertPlanInspection(planInspection);

        }

        return 1;
    }





    /**
     * 修改应急物资检查
     *
     * @param planInspection 应急物资检查
     * @return 结果
     */
    @Override
    public int updatePlanInspection(PlanInspection planInspection) {

        planInspection.setUpdateTime(DateUtils.getNowDate());
        planInspectionMapper.updatePlanInspection(planInspection);

        //更新头部表所选物资信息
        PlanInspection headMaterial = new PlanInspection();
        headMaterial.setInspectionHistoryId(planInspection.getInspectionHistoryId());

        List<PlanInspection> resultList=planInspectionMapper.selectPlanInspectionList(headMaterial);
        if(resultList !=null && resultList.size()>0){

            StringJoiner materialIdJoiner = new StringJoiner(",");
            StringJoiner materialNameJoiner = new StringJoiner(",");

            resultList.forEach(item -> {
                //将实体中的某个字段获取到 添加到stringJoiner
                materialIdJoiner.add(item.getMaterialId().toString());
                materialNameJoiner.add(item.getMaterialName());
            });

            String materialIds = materialIdJoiner.toString();
            String materialNames = materialNameJoiner.toString();

            PlanInspectionHistory planInspectionHistory = planInspectionMapper.getInspectionHistoryInfo(planInspection.getInspectionHistoryId());

            planInspectionHistory.setMaterialId(materialIds);
            planInspectionHistory.setMaterialName(materialNames);

            planInspectionMapper.updateInspectionHistory(planInspectionHistory);
        }

        return 1;
    }


    /**
     * 修改应急物资检查记录
     *
     * @param planInspectionHistory 应急物资检查记录
     * @return 结果
     */
    @Override
    public int updateInspectionHistory(PlanInspectionHistory planInspectionHistory) {
        planInspectionHistory.setUpdateTime(DateUtils.getNowDate());
        planInspectionHistory.setUpdateBy(SecurityUtils.getUserId()+"");

        planInspectionMapper.updateInspectionHistory(planInspectionHistory);

        Long inspectionHistoryId =planInspectionHistory.getId();

        String[] materialIds = planInspectionHistory.getMaterialId().split(",");


        planInspectionMapper.deletePlanInspectionByHistoryId(inspectionHistoryId);



        for (int i = 0; i < materialIds.length; i++) {


            Long id=Long.parseLong(materialIds[i].toString());
            PlanSupplies planSupplies = planSuppliesMapper.selectPlanSuppliesById(id);

            PlanInspection planInspection = new PlanInspection();
            //检查记录头部表主键
            planInspection.setInspectionHistoryId(inspectionHistoryId);
            //检查说明
            planInspection.setInspectionCertificate(planInspectionHistory.getProblemDescription());
            planInspection.setCycle(planInspectionHistory.getCycle());
            planInspection.setCreateTime(DateUtils.getNowDate());
            planInspection.setMaterialCode(planSupplies.getMaterialCode());
            planInspection.setPerformance("1");
            planInspection.setMaterialId(id);
            planInspection.setMaterialName(planSupplies.getMaterialName());
            planInspection.setCreateTime(DateUtils.getNowDate());
            planInspection.setCreateBy(SecurityUtils.getUserId()+"");
            planInspection.setUpdateBy(SecurityUtils.getUserId()+"");
            planInspection.setUpdateTime(DateUtils.getNowDate());
            planInspectionMapper.insertPlanInspection(planInspection);

        }

        return 1;





    }




    /**
     * 批量删除应急物资检查
     *
     * @param ids 需要删除的应急物资检查主键
     * @return 结果
     */
    @Override
    public int deletePlanInspectionByIds(Long[] ids) {
        return planInspectionMapper.deletePlanInspectionByIds(ids);
    }

    /**
     * 批量删除应急物资检查记录
     *
     * @param ids 需要删除的应急物资检查主键
     * @return 结果
     */
    @Override
    public int deleteInspectionHistoryByIds(Long[] ids) {

        planInspectionMapper.deletePlanInspectionByHistoryIds(ids);
        return planInspectionMapper.deleteInspectionHistoryByIds(ids);
    }





    /**
     * 删除应急物资检查信息
     *
     * @param id 应急物资检查主键
     * @return 结果
     */
    @Override
    public int deletePlanInspectionById(Long id) {
        return planInspectionMapper.deletePlanInspectionById(id);
    }

    @Override
    public Map<String, PlanInspection> selectPlanInspectionMap(List<String> materialCode) {
        if (CollectionUtils.isEmpty(materialCode)) return Collections.EMPTY_MAP;
        List<PlanInspection> planInspections = planInspectionMapper.getLastInspectTime(materialCode);
        return planInspections.stream().collect(Collectors.toMap(PlanInspection::getMaterialCode, Function.identity()));
    }
    // 定时 提醒应急物资检查
    @Override
    public void noticeMSG() {
        String year = LocalDate.now().getYear()+"";
        String moths = LocalDate.now().getMonthValue()+"";
        SysNoticeInfo sysNoticeInfo = new SysNoticeInfo();
        sysNoticeInfo.setTitle("应急物资检查");
        sysNoticeInfo.setContent("尊敬的用户，您" + year + "年" + moths + "月，应急物资检查时间到了，如若已经检查完毕请忽略此消息" );
        sysNoticeInfo.setUserId("1");
        remoteNoticeInfoService.add(sysNoticeInfo);
    }


    public List<PlanSuppliesDto> selectMater() {
            StringBuilder sb = new StringBuilder();
            String rummager = planInspectionMapper.rummagerList();
            List<PlanSuppliesDto> list = planSuppliesMapper.selectMater();
            for(int i=0;i<list.size();i++){
                sb.append(list.get(i).getMaterialName());
                sb.append(",").toString();
            }

            SysNoticeInfo sysNoticeInfo = new SysNoticeInfo();
            sysNoticeInfo.setTitle("上次检查没有检查的物资");
            sysNoticeInfo.setContent(sb.toString());
            if(rummager!=null && !"".equals(rummager)){
                sysNoticeInfo.setUserId(rummager);
            }
            remoteNoticeInfoService.add(sysNoticeInfo);
            return list;
    }
    public List<PlanInspection> selectMaterAll() {
        List<PlanInspection> list1 = planSuppliesMapper.selectMaterAll();
        String rummager = planInspectionMapper.rummagerList();
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<list1.size();i++){
            sb.append(list1.get(i).getMaterialName());
            sb.append(",").toString();
        }
        SysNoticeInfo sysNoticeInfo = new SysNoticeInfo();
        sysNoticeInfo.setTitle("上次检查过的物资");
        sysNoticeInfo.setContent(sb.toString());
        if(rummager!=null && !"".equals(rummager)){
            sysNoticeInfo.setUserId(rummager);
        }
        remoteNoticeInfoService.add(sysNoticeInfo);
        return list1;
    }
}
